package com.ainote.config; // 假设您在 config 包下创建

import io.github.cdimascio.dotenv.Dotenv;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;

import java.util.HashMap;
import java.util.Map;

public class DotenvInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        try {
            // 1. 加载 .env 文件
            Dotenv dotenv = Dotenv.configure()
                    .directory("./") // 在 backend 目录下查找
                    .ignoreIfMissing()
                    .load();

            // 2. 将加载的变量转换为 Map
            Map<String, Object> dotenvProperties = new HashMap<>();
            dotenv.entries().forEach(entry -> {
                // 将所有变量注入到 Spring 的 PropertySource 中
                dotenvProperties.put(entry.getKey(), entry.getValue());
            });

            // 3. 注册一个新的 PropertySource，确保它优先级足够高
            ConfigurableEnvironment environment = applicationContext.getEnvironment();
            environment.getPropertySources().addFirst(
                    new MapPropertySource("dotenvProperties", dotenvProperties)
            );

        } catch (Exception e) {
            System.err.println("WARN: Failed to load .env file via Initializer. Proceeding...");
        }
    }
}